package com.piggy.logi.sys.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.utils.RegexUtils;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.core.utils.poi.ExcelUtil;
import com.piggy.common.core.web.controller.BaseController;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.common.log.annotation.LogiLog;
import com.piggy.common.log.enums.BusinessType;
import com.piggy.common.satoken.annotation.Inner;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.logi.sys.api.domain.LogiSysRole;
import com.piggy.logi.sys.api.domain.LogiSysUser;
import com.piggy.logi.sys.enums.OrgTypeEnum;
import com.piggy.logi.sys.service.ILogiSysPermissionService;
import com.piggy.logi.sys.service.ILogiSysPostService;
import com.piggy.logi.sys.service.ILogiSysRoleService;
import com.piggy.logi.sys.service.ILogiSysUserService;
import com.piggy.oss.cloud.OSSFactory;
import com.piggy.sys.api.model.LoginUser;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author shark
 */
@RestController
@RequestMapping("/logi/user")
public class LogiSysUserController extends BaseController {
    @Resource
    private ILogiSysUserService userService;

    @Resource
    private ILogiSysRoleService roleService;

    @Resource
    private ILogiSysPostService postService;

    @Resource
    private ILogiSysPermissionService permissionService;

    /**
     * 获取用户列表
     */
    //@SaCheckPermission("system:user:list")
    @PostMapping("/list")
    public TableDataInfo<LogiSysUser> list(@RequestBody LogiSysUser user) {
        if (ObjectUtil.isEmpty(user.getDeptId())) {
            user.setDeptId(SecurityUtils.getDeptId());
        }
        return userService.selectPageUserList(user);
    }

    /**
     * 获取用户列表
     */
    //@SaCheckPermission("system:user:list")
    @Inner
    @PostMapping("/innerList")
    public TableDataInfo<LogiSysUser> innerList(@RequestBody LogiSysUser user) {
        startPage(user);
        List<LogiSysUser> list = userService.selectUserDeptExtList(user);
        return getDataTable(list);
    }

    @LogiLog(title = "用户管理", businessType = BusinessType.EXPORT)
    //@SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, LogiSysUser user) throws IOException {
        List<LogiSysUser> list = userService.selectUserList(user);
        ExcelUtil<LogiSysUser> util = new ExcelUtil<LogiSysUser>(LogiSysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @LogiLog(title = "用户管理", businessType = BusinessType.IMPORT)
    //@SaCheckPermission("system:user:import")
    @PostMapping("/importData")
    public R importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<LogiSysUser> util = new ExcelUtil<LogiSysUser>(LogiSysUser.class);
        List<LogiSysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return R.ok(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<LogiSysUser> util = new ExcelUtil<LogiSysUser>(LogiSysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/info/{username}")
    public R<LoginUser<LogiSysUser>> info(@PathVariable("username") String username) {
        if (StrUtil.isNotBlank(username) && RegexUtils.isMobile(username)) {
            return phone(username);
        }
        if (StrUtil.isNotBlank(username) && RegexUtils.isEmail(username)) {
            return email(username);
        }
        LogiSysUser logiSysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/phone/{phone}")
    public R<LoginUser<LogiSysUser>> phone(@PathVariable("phone") String phone) {
        LogiSysUser logiSysUser = userService.selectUserByPhone(phone);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/email/{email}")
    public R<LoginUser<LogiSysUser>> email(@PathVariable("email") String email) {
        LogiSysUser logiSysUser = userService.selectUserByEmail(email);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/dept/{username}")
    public R<LoginUser<LogiSysUser>> deptInfo(@PathVariable("username") String username,
                                              @RequestParam("dept") String dept) {
        if (StrUtil.isNotBlank(username) && RegexUtils.isMobile(username)) {
            return deptPhone(username, dept);
        }
        if (StrUtil.isNotBlank(username) && RegexUtils.isEmail(username)) {
            return deptEmail(username, dept);
        }
        LogiSysUser logiSysUser = userService.selectUserByUserNameAndDept(username, dept);
        if (StringUtils.isNull(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/dept/phone/{phone}")
    public R<LoginUser<LogiSysUser>> deptPhone(@PathVariable("phone") String phone,
                                               @RequestParam("dept") String dept) {
        LogiSysUser logiSysUser = userService.selectUserByPhoneAndDept(phone, dept);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/dept/email/{email}")
    public R<LoginUser<LogiSysUser>> deptEmail(@PathVariable("email") String email,
                                               @RequestParam("dept") String dept) {
        LogiSysUser logiSysUser = userService.selectUserByEmailAndDept(email, dept);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户名或密码错误");
        }
        return userInfo(logiSysUser);
    }

    private R<LoginUser<LogiSysUser>> userInfo(LogiSysUser logiSysUser) {
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(logiSysUser.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(logiSysUser.getUserId());
        LoginUser<LogiSysUser> sysUserVo = new LoginUser<>();
        sysUserVo.setSysUser(logiSysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/sys/{username}")
    public R<LogiSysUser> sysUser(@PathVariable("username") String username) {

        if (StrUtil.isBlank(username)) {
            return R.fail("用户名不能为空");
        }

        LogiSysUser logiSysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(logiSysUser)) {
            return R.fail("用户名不存在");
        }

        return R.ok(logiSysUser);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R getInfo() {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> ajax = new HashMap<>(3);
        LogiSysUser user = userService.selectUserById(userId);
        user.setRoles(roleService.selectRoleAll(SecurityUtils.getMainDeptId()));
        user.setPosts(postService.selectPostAll());
        user.setPostIds(postService.selectPostListByUserId(userId));
        user.setRoleIds(roleService.selectRoleIdsByUserId(userId));
        if (ObjectUtil.isEmpty(user)) {
            return R.fail("用户不存在");
        }
        String avatar = OSSFactory.build().buildUrl(user.getAvatar());
        user.setAvatar(avatar);
        ajax.put("user", user);
        ajax.put("roles", roles);
        if (SecurityUtils.isAdmin(userId)) {
            //999 超级管理员
            ajax.put("orgType", OrgTypeEnum.SYSADMIN.getCode());//返回给前端判断用
            ajax.put("orgTypeName", "超级管理员");
        } else {
            if (SecurityUtils.isAdmin(userId)) {
                //999 超级管理员
                ajax.put("orgType", OrgTypeEnum.SYSADMIN.getCode());//返回给前端判断用
                ajax.put("orgTypeName", OrgTypeEnum.SYSADMIN.getInfo());
            } else {
                //0 未知
                ajax.put("orgType", OrgTypeEnum.UNKNOWN.getCode());
                ajax.put("orgTypeName", OrgTypeEnum.UNKNOWN.getInfo());
            }
        }
        ajax.put("permissions", permissions);
        return R.ok(ajax);
    }

    /**
     * 根据用户编号获取详细信息
     */
    ////@SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public R<LogiSysUser> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        if (Objects.isNull(userId)) {
            userId = SecurityUtils.getUserId();
        }
        LogiSysUser user = userService.selectUserById(userId);
        userService.checkUserDataScope(userId);
        List<LogiSysRole> roles = roleService.selectRoleAll(SecurityUtils.getMainDeptId());
        user.setRoles(roles);
        user.setPosts(postService.selectPostAll());
        user.setPostIds(postService.selectPostListByUserId(userId));
        user.setRoleIds(roleService.selectRoleIdsByUserId(userId));
        return R.ok(user);

    }

    /**
     * 根据用户编号获取详细信息
     */
    ////@SaCheckPermission("system:user:query")
    @GetMapping(value = {"infoById/", "infoById/{userId}"})
    public R<Map<String, Object>> getInfoById(@PathVariable(value = "userId", required = false) Long userId) {
        Map<String, Object> ajax = new HashMap<>();
        List<LogiSysRole> roles = roleService.selectRoleAll(SecurityUtils.getMainDeptId());
        ajax.put("roles", SecurityUtils.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put("user", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return R.ok(ajax);
    }

    /**
     * 新增用户
     */
    //@SaCheckPermission("system:user:add")
    @LogiLog(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody LogiSysUser user) {
        /*if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else */
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("新增用户【" + user.getPhonenumber() + "】失败，手机号码已存在");
        } /*else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }*/
        user.setCreateBy(SecurityUtils.getPhone());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 新增用户
     */
    //@SaCheckPermission("system:user:add")
    @Inner
    @LogiLog(title = "服务商用户注册&部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/bossAdd")
    public R bossAdd(@Validated @RequestBody LogiSysUser user) {

        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("新增用户【" + user.getPhonenumber() + "】失败，手机号码已存在");
        } /*else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }*/
        user.setCreateBy("admin");
        user.setCreateTime(new Date());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    //@SaCheckPermission("system:user:edit")
    @LogiLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody LogiSysUser user) {
//        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("修改用户【" + user.getPhonenumber() + "】失败，手机号码已存在");
        } /*else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }*/
        user.setUpdateBy(SecurityUtils.getPhone());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 修改用户
     */
    //@SaCheckPermission("system:user:edit")
    @LogiLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateUserBasic")
    public R<Integer> updateUserBasic(@Validated @RequestBody LogiSysUser user) {
        if (StrUtil.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("修改用户【" + user.getPhonenumber() + "】失败，手机号码已存在");
        } /*else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }*/
        return toAjax(userService.updateUserBasic(user));
    }

    /**
     * 删除用户
     */
    //@SaCheckPermission("system:user:remove")
    @LogiLog(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R remove(@PathVariable Long[] userIds) {
        return R.ok(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    //@SaCheckPermission("system:user:edit")
    @LogiLog(title = "重置密码", businessType = BusinessType.INSERT)
    @PutMapping("/resetPwd")
    public R resetPwd(@RequestBody LogiSysUser user) {
        //userService.checkUserAllowed(user);
        user.setOrignalPwd(user.getPassword());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getPhone());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    //@SaCheckPermission("system:user:edit")
    @LogiLog(title = "状态修改", businessType = BusinessType.INSERT)
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody LogiSysUser user) {
        //userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getPhone());
        return toAjax(userService.updateUserStatus(user));
    }

    @Inner
    @GetMapping("/getUser/{deptId}")
    public R<List<LogiSysUser>> getUserByDeptId(@PathVariable(value = "deptId", required = false) Long deptId) {
        return R.ok(userService.getUserByDeptId(deptId));
    }

    @Inner
    @GetMapping("/getUserByDeptIds")
    public R<List<LogiSysUser>> getUserByDeptIds(@RequestParam("deptIds") List<Long> deptIds) {
        return R.ok(userService.getUserByDeptIds(deptIds));
    }

    @Inner
    @PostMapping("/queryUserAll/{mainDeptId}")
    public R<List<LogiSysUser>> queryUserAll(@PathVariable(value = "mainDeptId") Long mainDeptId) {
        return R.ok(userService.queryUserAll(mainDeptId));
    }

    @Inner
    @GetMapping("/getUsersByPhoneNumber")
    public R<List<LogiSysUser>> getUsersByPhoneNumber(@RequestParam("phoneNumber") String phoneNumber) {
        return R.ok(userService.getUsersByPhoneNumber(phoneNumber));
    }

    @Inner
    @GetMapping("/getUserByID")
    public R<LogiSysUser> getUserByID(@RequestParam("userId") Long userId) {
        return R.ok(userService.getById(userId));
    }

    /**
     * 根据用户编号获取授权角色
     */
    //@SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public R authRole(@PathVariable("userId") Long userId) {
        LogiSysUser user = userService.selectUserById(userId);
        List<LogiSysRole> roles = roleService.selectRolesByUserId(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        return R.ok(map);
    }

    /**
     * 用户授权角色
     */
    //@SaCheckPermission("system:user:edit")
    @LogiLog(title = "用户授权角色", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public R insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 用户注册
     */
    @Inner
    @LogiLog(title = "用户注册", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public R<LogiSysUser> register(@RequestBody LogiSysUser user) {
        user.setDeptId(0L);
        /*if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }*/
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("注册用户【" + user.getPhonenumber() + "】失败，账号已存在！");
        }
        return R.ok(userService.register(user));
    }

    @LogiLog(title = "用户重置密码", businessType = BusinessType.INSERT)
    @GetMapping("/resetPwd/{phone}")
    public R<Integer> resetPwd(@PathVariable("phone") String phone,
                               @RequestParam("passwd") String passwd,
                               @RequestParam("dept") String dept) {
        LogiSysUser logiSysUser = userService.selectUserByPhoneAndDept(phone, dept);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户【"+phone+"】不存在");
        }

        LogiSysUser update = new LogiSysUser().
                setUserId(logiSysUser.getUserId()).
                setOrignalPwd(passwd);
        update.setPassword(SecurityUtils.encryptPassword(update.getOrignalPwd()));
        update.setMainDept(dept);
        return toAjax(userService.resetPwd(update));
    }

    @LogiLog(title = "服务商用户重置密码", businessType = BusinessType.INSERT)
    @GetMapping("/resetMainUserPwd/{phone}")
    @Inner
    public R<Integer> resetMainUserPwd(@PathVariable("phone") String phone,
                               @RequestParam("passwd") String passwd) {
        LogiSysUser logiSysUser = userService.selectMainUserByPhone(phone);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户【"+phone+"】不存在");
        }

        LogiSysUser update = new LogiSysUser().
                setUserId(logiSysUser.getUserId()).
                setOrignalPwd(passwd);
        update.setPassword(SecurityUtils.encryptPassword(update.getOrignalPwd()));
        return toAjax(userService.resetPwd(update));
    }

    @GetMapping("/getMainUser/{phone}")
    @Inner
    public R<LogiSysUser> resetMainUserPwd(@PathVariable("phone") String phone) {
        LogiSysUser logiSysUser = userService.selectMainUserByPhone(phone);
        if (ObjectUtil.isEmpty(logiSysUser)) {
            return R.fail("用户【"+phone+"】不存在");
        }
        return R.ok(logiSysUser);
    }

    @ApiOperation("更新用户手机号码")
    @LogiLog(title = "更新用户手机号码")
    @GetMapping("/changeUserPhone")
    public R<LogiSysUser> changeUserPhone(@RequestParam("oldPhoneCode") String oldPhoneCode,
                                          @RequestParam("newPhone") String newPhone,
                                           @RequestParam("phoneCode") String phoneCode) {
        LogiSysUser logiSysUser = userService.changeUserPhone(SecurityUtils.getPhone(), oldPhoneCode, newPhone, phoneCode);
        return R.ok(logiSysUser);
    }

}
